package vng.wcc.sonph.LauncherGenerator;

import android.content.Context;
import android.widget.LinearLayout;

public class LauncherScreenView extends LinearLayout {

	private Formatter formatter;
	private CellInfo[] data;
	private int numColsPerPage;

	/**
	 * LauncherScreenView is a page, it contains several rows, 
	 * each row contains at most numColsPerPage items  
	 * @param context
	 * @param data contains information about the items to be displayed (icon,title and intent to launch)
	 * @param formatter provides layout information 
	 * @param numColsPerPage number of columns per row on each page
	 */
	public LauncherScreenView(Context context,CellInfo[] data,Formatter formatter,int numColsPerPage) {
		super(context);
		this.data = data;
		this.formatter = formatter;
		this.numColsPerPage = numColsPerPage;
		initView();
	}

	private void initView() {
		setViewLayout();
		addChildren();
	}

	/**
	 * Add children rows of this screen
	 */
	private void addChildren() {		

		if ( data.length == 0 ) return;				
		int originalIndex = 0;
		CellInfo[] rowData = new CellInfo[this.numColsPerPage];
		
		int nrows = (data.length - 1)/ numColsPerPage + 1;
		
		for(int rowIndex  = 0 ; rowIndex < nrows ; rowIndex++) {		
			//reinitialize the rowData - null element won't be represent on the row 
			for(int i = 0 ; i < rowData.length ; i++) rowData[i] = null;
			
			for(int colIndex =  0; colIndex < numColsPerPage ; colIndex++) {
				rowData[colIndex] = data[originalIndex];
				originalIndex++;
				
				//no more data to show
				if (originalIndex >= data.length) break;
			}
			
			addRow(rowData);			
		}
	}

	/**
	 * Create a row from the data for that row
	 * @param tempData contains items information the row to create
	 */
	private void addRow(CellInfo[] tempData) {
		LauncherRowView currentRow = new LauncherRowView(this.getContext(), formatter, tempData);
		this.addView(currentRow, formatter.getRowWidth(), formatter.getRowHeight());
	}

	private void setViewLayout() {
		this.setPadding(0, formatter.getLauncherTopPadding(), 0, 0);
		this.setOrientation(LinearLayout.VERTICAL);
	}

}
